
<template>
  <!-- 营销项目管理->项目总结抽检 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="conditionFilter"
      :list="topFilterInit"
      :cols="3"
      labelWidth="110"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
      columnsRef="projectOperating_summary_oemCheck_index_01"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-download" @click="batchPass">批量通过</el-button>
      </template>
    </FilterTable>

    <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealerMadal
        selectType="multiple"
        v-model="initDealerData"
        :deptId="orgId"
        :dealerType="dealerType"
        ref="dealerDialog"
        @close="closeDealer"
      />
    </BaseDialog>

    <Drawer
      :visible.sync="visibleDrawer"
      title="项目总结抽检"
      destroyOnClose
      :containerStyle="{width:'70vw',minWidth:'1000px',height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <info-modal v-model="initData" :rowData="formData" @close="drawerClose" />
    </Drawer>
    <!-- 选择方案 -->
    <BaseDialog
      title="选择项目"
      :visible.sync="visibleDialogPro"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <programModal selectType="single" @close="selectModelBackPro" />
    </BaseDialog>
    <!-- 选择车型 -->
    <BaseDialog
      title="选择车型"
      :visible.sync="visibleDialog"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <modalModal selectType="multiple" @close="selectModelBack" />
    </BaseDialog>
  </div>
</template>

<script>
import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire'; //获取登录信息
import { exportExcelFile } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import infoModal from './info';
import { getRegion } from '@/api/cms-common/dealerdata/index';
import dealerMadal from '@/pages/cms-common/dealerdata/dealerType';
import programModal from '../../program/push/select';
import modalModal from '@/pages/cms-common/model';
import { formatdateByDay } from '@/utils/index';
import { region } from '@/api/cms-common/region';
import { batchPassAll, getBigMarketType, getSmallMarketType, getSummaryOemInquireList, getSummaryOemInquireExcelList, selectListByBill } from '@/api/cms-api/projectOperating/plan/index';
export default {
  mixins: [dictionary, region],
  components: {
    infoModal,
    dealerMadal,
    programModal,
    modalModal
  },
  //初始化数据  全局变量
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      isSelectColumn: true,
      visibleDrawer: false,
      fetchParams: { isCheck: 1 }, //参数
      fetchApi: getSummaryOemInquireList, //ipa 接口
      visibleDealer: false,
      initDealerData: {}, //经销商弹窗参数
      dataSource: [], //返回经销商数组
      formData: {},
      initData: {},
      idsOK: [], //批量通过的ids
      visibleDialogPro: false,
      visibleDialog: false,
      statusOK: [], //批量选中数据的状态
      orgId: null, //登录人所属组织
      dealerType: '25381001,25381002,25381003,25381004,25381005' //不包含大客户的
    };
  },
  //方法、事件
  methods: {
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      let ids = []; //批量提报的ids
      for (let j = 0; j < this.selectedRows.length; j++) {
        ids.push(this.selectedRows[j].planId);
      }
      this.idsOK = ids;
      let statusSelect = []; //批量选中数据的状态
      //选中数据的状态
      for (let k = 0; k < this.selectedRows.length; k++) {
        statusSelect.push(this.selectedRows[k].slotCheckStatus);
      }
      this.statusOK = statusSelect;
    },
    //批量通过
    async batchPass() {
      let result = {};
      if (this.idsOK.length > 0) {
        // console.log(this.statusOK);
        // for (let i = 0; i < this.statusOK.length; i++) {
        //   if (this.statusOK[i] != null) {
        //     this.$notify.warning({ title: '提示信息', message: '只有未曾抽检的才能进行批量通过！' });
        //     return;
        //   }
        // }
        this.$confirm('确定批量通过吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          result = await batchPassAll(this.idsOK);
          if (result.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '批量通过成功!' });
            this.fetchParams = { ...this.fetchParams };
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '批量通过失败!' });
          }
        });
      } else {
        this.$notify.warning({ title: '提示信息', message: '请勾选需要通过的项目总结!' });
      }
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'SELECT', label: '事业部', fieldName: 'sourceDept', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'INPUT',
          label: '项目方案',
          fieldName: 'projectProgramName',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialogPro()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '项目状态',
          fieldName: 'planStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictListRemoveCodes('2531', [
            '25311001',
            '25311002',
            '25311003',
            '25311004',
            '25311005',
            '25311006',
            '25311007',
            '25311008',
            '25311010',
            '25311011',
            '25311012',
            '25311013'
          ])
        },
        { type: 'INPUT', label: '项目编号', fieldName: 'planCode', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '项目名称', fieldName: 'projectName', placeholder: '请输入', initialValue: '' },
        { type: 'RANGE_DATE', label: '项目执行开始日期', fieldName: 'realStartDate', initialValue: '', placeholder: '请选择' },
        { type: 'RANGE_DATE', label: '项目月份', fieldName: 'activityMonth', dateType: 'monthrange', initialValue: '', placeholder: '请选择' },
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'dealerName',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openDialog()}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modal',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialog()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '项目大类',
          fieldName: 'projectMainClass',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: value => {
            this.initMarketTypeSmall(value);
          }
        },
        { type: 'SELECT', label: '项目小类', fieldName: 'projectSmallClass', placeholder: '请选择', initialValue: '', itemList: [] },
        { type: 'SELECT', label: '合作方式', fieldName: 'cooperationMethod', placeholder: '请选择', initialValue: '', itemList: this.createDictList('2532') },
        { type: 'SELECT', label: '是否变更报备', fieldName: 'isChangePlan', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1004') },
        { type: 'SELECT', label: '是否抽检', fieldName: 'isCheck', placeholder: '请选择', initialValue: '', itemList:[{ text: '是', value: '是' }, { text: '否', value: '否' }]}
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            if (props.row.planStatus == 25311009 || props.row.slotCheckStatus == null) {
              return (
                <div>
                  <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'edit')}>
                    抽检
                  </el-button>
                </div>
              );
            } else {
              return (
                <div>
                  <el-button size="mini" type="text" disabled onClick={() => this.drawerHandle(props.row, 'edit')}>
                    抽检
                  </el-button>
                </div>
              );
            }
          }
        },
        { title: '是否抽检', dataIndex: 'isCheck',   sorter: true },
        { title: '项目编号', dataIndex: 'planCode', sorter: true },
        {
          title: '项目状态',
          dataIndex: 'planStatus',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.planStatus, '2531')}</span>;
          }
        },
        // { title: '事业部', dataIndex: 'orgId', sorter: true, hidden: true },
        { title: '事业部', dataIndex: 'orgName', sorter: true },
        { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
        { title: '经销商简称', dataIndex: 'dealerShortname', sorter: true },
        { title: '经销商名称', dataIndex: 'dealerName', sorter: true },
        {
          title: '省份',
          dataIndex: 'provinceId',
          sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.provinceId)}</span>;
          }
        },
        {
          title: '城市',
          dataIndex: 'cityId',
          sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.cityId)}</span>;
          }
        },
        { title: '计划项目金额', dataIndex: 'planProjectAmount', sorter: true, numberFormat: true },
        { title: '计划批准金额', dataIndex: 'planApproveAmount', sorter: true, numberFormat: true },
        {
          title: '计划核销比例',
          dataIndex: 'planCancellationRatio',
          sorter: true,
          render: props => {
            if (props.row.planCancellationRatio == null) {
              return <span slot="append">{props.row.planCancellationRatio}</span>;
            } else {
              return <span slot="append">{props.row.planCancellationRatio}%</span>;
            }
          }
        },
        { title: '实际项目金额', dataIndex: 'realProjectAmount', sorter: true, numberFormat: true },
        { title: '实际批准金额', dataIndex: 'realApproveAmount', sorter: true, numberFormat: true },
        {
          title: '实际核销比例',
          dataIndex: 'realCancellationRatio',
          sorter: true,
          render: props => {
            if (props.row.realCancellationRatio != null) {
              return <span slot="append">{props.row.realCancellationRatio}%</span>;
            }
          }
        },
        {
          title: '合作方式',
          dataIndex: 'cooperationMethod',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.cooperationMethod, '2532')}</span>;
          }
        },
        { title: '计划支持场次/投放天数', dataIndex: 'planTimeDay', sorter: true },
        { title: '实际支持场次/投放天数', dataIndex: 'realTimeDay', sorter: true },
        { title: '目标订单数', dataIndex: 'targetOrderNum', sorter: true },
        { title: '目标集客数', dataIndex: 'targetGuestsNum', sorter: true },
        { title: '目标留档数', dataIndex: 'targetRetentionNum', sorter: true },
        { title: '实际订单数', dataIndex: 'realOrderNum', sorter: true },
        { title: '实际集客数', dataIndex: 'realGuestsNum', sorter: true },
        { title: '实际留档数', dataIndex: 'realRetentionNum', sorter: true },
        {
          title: '项目月份',
          dataIndex: 'activityMonth',
          sorter: true,
          dateFormat: 'YYYY年MM月'
          // render: props => {
          //   return <span>{this.formatDatesNoDay(props.row.activityMonth)} </span>;
          // }
        },
        { title: '项目车型', dataIndex: 'modelLists', sorter: true },
        { title: '项目大类', dataIndex: 'projectMainClassName', sorter: true },
        { title: '项目小类', dataIndex: 'projectSmallClassName', sorter: true },
        { title: '项目名称', dataIndex: 'projectName', sorter: true },
        { title: '方案编号', dataIndex: 'programCode', sorter: true },
        { title: '方案名称', dataIndex: 'programName', sorter: true },
        {
          title: '开始日期',
          dataIndex: 'realStartDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.realStartDate)} </span>;
          }
        },
        {
          title: '结束日期',
          dataIndex: 'realEndDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.realEndDate)} </span>;
          }
        },
        {
          title: '是否变更报备',
          dataIndex: 'isChangePlan',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.isChangePlan, '1004')}</span>;
          }
        }
      ];
    },
    //日期格式化年月
    formatDatesNoDay: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      return year + '-' + month;
    },
    //日期格式化年月日
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    //详情
    async drawerHandle(row, type) {
      let res = {};
      let res1 = {};
      let res2 = {};
      let res3 = {};
      let res4 = {};
      let res5 = {};
      let res6 = {};
      //逻辑自己写
      this.initData = {
        row: row,
        type: type //add/edit/show
      };
      this.formData = row;
      //现场高清照片
      let fileParams = { planId: this.formData.planId, billType: 25791001 };
      res = await selectListByBill(fileParams);
      if (res.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res.data.length; j++) {
          let o1 = { name: res.data[j].fileName };
          let o2 = { url: res.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { photoUrl: caseUrlList }, this.initData.row);
      }
      //项目核销材料
      let fileParams1 = { planId: this.formData.planId, billType: 25791002 };
      res1 = await selectListByBill(fileParams1);
      if (res1.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res1.data.length; j++) {
          let o1 = { name: res1.data[j].fileName };
          let o2 = { url: res1.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { cancellationUrl: caseUrlList }, this.initData.row);
      }
      //实际使用费用明细
      let fileParams2 = { planId: this.formData.planId, billType: 25791003 };
      res2 = await selectListByBill(fileParams2);
      if (res2.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res2.data.length; j++) {
          let o1 = { name: res2.data[j].fileName };
          let o2 = { url: res2.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { feeDetailUrl: caseUrlList }, this.initData.row);
      }
      //合同报价单
      let fileParams3 = { planId: this.formData.planId, billType: 25791004 };
      res3 = await selectListByBill(fileParams3);
      if (res3.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res3.data.length; j++) {
          let o1 = { name: res3.data[j].fileName };
          let o2 = { url: res3.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { contractOfferUrl: caseUrlList }, this.initData.row);
      }
      //发票
      let fileParams4 = { planId: this.formData.planId, billType: 25791005 };
      res4 = await selectListByBill(fileParams4);
      if (res4.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res4.data.length; j++) {
          let o1 = { name: res4.data[j].fileName };
          let o2 = { url: res4.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { billUrl: caseUrlList }, this.initData.row);
      }
      //报备附件
      let fileParams5 = { planId: this.formData.planId, billType: 25791006 };
      res5 = await selectListByBill(fileParams5);
      if (res5.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res5.data.length; j++) {
          let o1 = { name: res5.data[j].fileName };
          let o2 = { url: res5.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { reportUrl: caseUrlList }, this.initData.row);
      }
      //其它
      let fileParams6 = { planId: this.formData.planId, billType: 25791007 };
      res6 = await selectListByBill(fileParams6);
      if (res6.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res6.data.length; j++) {
          let o1 = { name: res6.data[j].fileName };
          let o2 = { url: res6.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { otherUrl: caseUrlList }, this.initData.row);
      }
      this.visibleDrawer = true;
    },
    //关闭详情
    drawerClose(val, type) {
      this.visibleDrawer = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //获取事业部下拉列表数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterInit[0].itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    //经销商窗口关闭，返回数据
    closeDealer(data) {
      if (data.data && data.data.length > 0) {
        //清空数据内容
        this.dealerCode = '';
        this.dealerName = '';
        //循环返回数据
        data.data.forEach(x => {
          //插入经销商id
          // this.dealerList.push(x.dealerId);
          //使用逗号分隔拼接经销商ID
          if (this.dealerCode == '') {
            this.dealerCode = x.dealerCode;
          } else {
            this.dealerCode += ',' + x.dealerCode;
          }

          // this.dealerList.push(x.dealerId);
          //使用逗号分隔拼接经销商名称
          if (this.dealerName == '') {
            this.dealerName = x.dealerName;
          } else {
            this.dealerName += ',' + x.dealerName;
          }
        });
        this.topFilterInit[7].initialValue = this.dealerName;
      }
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //打开经销商弹窗
    openDialog() {
      this.initDealerData = {
        excludeBigCustomer: false, //是否查询大客户经销商，如果查询 true，不查询 false
        id: 1001
      };
      this.visibleDealer = true;
    },
    //搜索回调
    changeHandle(data) {
      //开始日期
      let realStartDate = data.realStartDate;
      //项目月份
      let activityMonth = data.activityMonth;
      data = Object.assign({}, { timestart: realStartDate[0] }, data);
      data = Object.assign({}, { timeend: realStartDate[1] }, data);
      data = Object.assign({}, { activityMonthStart: activityMonth[0] }, data);
      data = Object.assign({}, { activityMonthEnd: activityMonth[1] }, data);
      data = Object.assign({}, { isCheck: 1 }, data);
      data = Object.assign({}, { dealerCode: this.dealerCode }, data);
      data = Object.assign({ projectProgramId: this.projectProgramId, modelIdList: this.modelIdList }, data);
      this.dealerCode = '';
      this.modelIdList = '';
      this.projectProgramId = '';
      this.fetchParams = Object.assign({}, data);
    },
    //取项目大类
    async initBigMarketType() {
      let res = [];
      let rd = await getBigMarketType();
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.topFilterInit[9].itemList = res;
    },
    //取项目小类
    async initMarketTypeSmall(parentTypeId) {
      let res = [];
      this.topFilterInit.find(item => item.fieldName === 'projectSmallClass').initialValue = '';
      this.topFilterInit.find(item => item.fieldName === 'projectSmallClass').itemList = [];
      if (parentTypeId != '') {
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getSmallMarketType(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
        }
        this.topFilterInit[10].itemList = res;
      }
    },
    //项目方案弹窗打开
    openModelDialogPro() {
      this.visibleDialogPro = true;
    },
    //项目弹窗关闭
    selectModelBackPro(data) {
      // console.log('---data:', data);
      if (data && data.data && typeof data.data != null) {
        this.projectProgramId = data.data[0].projectProgramId;

        this.topFilterInit[1].initialValue = data.data[0].programName;
      }

      this.visibleDialogPro = false; //关闭弹窗
    },
    //车型弹窗打开
    openModelDialog() {
      this.visibleDialog = true;
    },
    //车型弹窗关闭
    selectModelBack(data) {
      if (data && data.data && typeof data.data != null) {
        //清空数据
        this.modelIdList = '';
        this.modelName = '';
        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接车型ID
          if (this.modelIdList == '') {
            this.modelIdList = x.modelId;
          } else {
            this.modelIdList += ',' + x.modelId;
          }

          //使用逗号分隔拼接车型名称
          if (this.modelName == '') {
            this.modelName = x.modelName;
          } else {
            this.modelName += ',' + x.modelName;
          }
        });

        //显示车型名称
        this.topFilterInit[8].initialValue = this.modelName;
      }

      this.visibleDialog = false; //关闭弹窗
    },
    async getUserInfo() {
      this.loginUser = await getLoginUser({});
      if (this.loginUser != null && this.loginUser != undefined) {
        if (this.loginUser.data.orgType == 15061005) {
          //是事业部
          this.orgId = this.loginUser.data.orgId;
        }
        // if (this.loginUser.data.orgType == 15061007) {
        //办事处 获取父类ID，赋给orgId
        // this.orgId = this.loginUser.data.orgId;
        // }
      }
    }
  },
  created() {
    //获取事业部下拉列表
    this.getDeptData();
    this.getUserInfo();
  },
  mounted() {
    //初始化项目大类
    this.initBigMarketType();
  }
};
</script>

<style scoped>
</style>
